<template>
  <div class="AdvancedSearchConfigDialog"
    :class="{
      moving: moving,
      isNewViewDialog: isNewView
    }"
    v-show="dialogVisible"
  >
    <div class="header">
      <div class="title">
        <span>{{$t('public.searchSettings')}}</span>
        <i class="iconfont icon-qiapianshangdeguanbi"
          style="
            float: right;
            font-size: 14px;
            cursor: pointer
          "
          @click="close()"
        />
      </div>
      <div class="sub-title">{{$t('public.searchSettingsDescribe')}}</div>
    </div>
    <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.advancedSearchCustomLayoutDialog">
      <div class="novice-circle-group " style="position: absolute;top: 15px;right: 225px">
        <div class="novice-circle4"></div>
        <div class="novice-circle3"></div>
        <div class="novice-circle2"></div>
        <div class="novice-circle1"></div>
        <div data-v-482275ab="" style="
          height: 100px;
          width: 50px;
          position: absolute;
          top: -35px;
          left: -50px;
        "></div>
      </div>
      <div style="position: absolute;top: -15px;left: -315px; padding-bottom: 10px;z-index: 100;">
        <novice-boot
          NoviceKey="advancedSearchCustomLayoutDialog"
          :NoviceArr="[{title: '', text: $t('public.searchSettingsNovice2')}]"
          @updateGuidanceSuccess="updateGuidanceSuccess"
        ></novice-boot>
      </div>
    </div>
    <div class="draggable-list-wrapper-header">
      <span>{{$t('public.searchOptionsField')}}</span>
      <span style="float: right;">{{$t('public.searchSettingsItemHidden')}} / {{$t('public.searchSettingsItemShow')}}</span>
    </div>
    <div class="draggable-list-wrapper">
      <draggable  element="ol" ref="draggable"
        :list="formItemList"
        :move="handleDraggableMoved"
        @choose="handleDraggableChoose"
        @end="handleDraggableEnd"
        @mouseup.native="handleDraggableEnd"
      >
        <li v-for="(item, index) in formItemList" class="item"
          :key="index"
          :data-item="JSON.stringify(item)"
          :class="{
            'current-item' : item.name === currentItemName,
            'is-hidden' : item.hidden
          }"
          :style="{
            display: (item.name && item.name.endsWith('_END'))||item.name=='textFieldContent' ? 'none' : ''
          }"
        >
          <i class="iconfont icon-shunxutuozhuai"/>
          <span class="name">{{item.label}}</span>
          <el-switch :width="24"
                     :disabled="itemsDisabled &&
                     itemsDisabled[activeName] &&
                     itemsDisabled[activeName][item.name]"
                     :value="!item.hidden"
                     @change="itemChange(item,formItemList)"></el-switch>
          <!-- <span class="button"
            style="
              float: right;
              cursor: pointer;
              user-select: none;
            "
            @click="item.hidden = !item.hidden"
          >{{item.hidden? $t('public.searchSettingsItemShow') : $t('public.searchSettingsItemHidden') }}</span> -->
        </li>
      </draggable>
    </div>
    <div class="dialog-footer">
      <el-button class="primary_btn" @click="close()">{{$t('public.cancel')}}</el-button>
      <el-button class="primary_btn" type="primary" @click="confirm()">{{$t('public.confirm')}}</el-button>
    </div>
  </div>
</template>

<script>
import { deepClone } from '@/utils/m7Utils.js'
import { debounce, throttle } from 'lodash'
import draggable from 'vuedraggable'
import noviceBoot from '@/components/public-modules/novice-boot/index.vue'

export default {
  name: 'AdvancedSearchConfigDialog',
  data () {
    return {
      dialogVisible: false,
      formItemList: [],
      getNoviceKeyStatus: {}
    }
  },
  components: {
    draggable,
    noviceBoot
  },
  props: {
    formItems: Array,
    currentItemName: String,
    searchType: String,
    formItemsConfig: Object,
    moving: Boolean,
    activeName: String,
    isNewView: Boolean
  },
  inject: {
    itemsDisabled: {
      default: () => {
      }
    }
  },
  computed: {
    // currentItem () {},
    currentIndex () {
      return this.formItemList.findIndex(d => {
        d.name === this.currentItemName
      })
    }
  },
  watch: {
    formItems: {
      handler: 'generateFormItemList',
      deep: true,
      immediate: true
    },
    formItemsConfig: {
      handler: 'generateFormItemList',
      deep: true,
      immediate: true
    },
    dialogVisible: {
      handler (dialogVisible) {
        this.$emit('update:dialogVisible', dialogVisible)
        // var myModal = document.getElementById('my-modal')

        // if (myModal) {
        //   if (dialogVisible) {
        //     myModal.style.display = 'block'
        //   } else {
        //     myModal.style.display = 'none'
        //   }
        // }

        if (dialogVisible) {
          this.addDocumentKeyEventListener()
        } else {
          this.removeDocumentKeyEventListener()
        }
      },
      deep: true,
      immediate: true
    },
    formItemList: {
      handler () {
        if (!this.dialogVisible) {
          return
        }
        var result = {}

        var formItemList = this.formItemList.filter(item => item.name && !item.name.endsWith('_END'))

        formItemList.forEach((item, index) => {
          result[item.name] = deepClone(item)
          result[item.name].order = index
        })

        this.$emit('editingFormItemsConfigChange', result)
      },
      deep: true
    }
  },
  methods: {
    generateFormItemList () {
      var resultList = []

      var formItemsConfig = this.formItemsConfig
      var formItems = deepClone(this.formItems)

      formItems.sort((aItem, bItem) => {
        var aOrder
        var bOrder
        var config

        if (formItemsConfig && formItemsConfig[aItem.name]) {
          config = formItemsConfig[aItem.name]
          aOrder = config.order
        }

        if (formItemsConfig && formItemsConfig[bItem.name]) {
          config = formItemsConfig[bItem.name]
          bOrder = config.order
        }

        function isNum (n) {
          return !isNaN(n)
        }

        if (isNum(aOrder) && !isNum(bOrder)) {
          return -1
        }

        if (!isNum(aOrder) && isNum(bOrder)) {
          return 1
        }

        if (isNum(aOrder) && isNum(bOrder)) {
          return aOrder - bOrder
        }

        return aItem._index - bItem._index
      })

      formItems && formItems.forEach((item, index) => {
        var newItem = {
          label: item.label,
          name: item.name,
          hidden: false
        }

        if (formItemsConfig && formItemsConfig[item.name]) {
          var config = formItemsConfig[item.name]
          let itemsDisabled = this.itemsDisabled || {}
          // 如果该字段默认disabled，则不隐藏
          newItem.hidden = itemsDisabled[this.activeName] &&
            itemsDisabled[this.activeName][item.name] ? false : config.hidden
        } else {
          newItem.hidden = false
        }
        resultList.push(newItem)
      })
      this.formItemList = resultList
    },
    handleDraggableChoose (event) {
      var name = ''

      if (
        event &&
        event.item &&
        event.item.dataset &&
        event.item.dataset.item
      ) {
        name = JSON.parse(event.item.dataset.item).name
      }
      this.$emit('update:currentItemName', name)
      this.$emit('update:moving', true)
    },
    handleDraggableEnd () {
      this.$emit('update:currentItemName', '')
      this.$emit('update:moving', false)
    },
    handleDraggableMoved (event) {
      if (!this.$_debounce) {
        this.$_debounce = debounce(() => {
          var ol = this.$refs.draggable.$el
          var lis = ol.getElementsByTagName('li')
          var items = []

          for (var i = 0; i < lis.length; i++) {
            var li = lis.item(i)
            if (li.style.display === 'none') {
              if(JSON.parse(li.dataset.item).name=='textFieldContent'){
                items.push(JSON.parse(li.dataset.item))
              }
            } else {
              items.push(JSON.parse(li.dataset.item))
            }
          }

          var result = {}

          items.forEach((item, index) => {
            result[item.name] = deepClone(item)
            result[item.name].order = index
          })

          this.$emit('editingFormItemsConfigChange', result)
        }, 100)
      }

      this.$_debounce()
    },
    handleKeydown: throttle(function (event) {
      if (this.currentIndex >= 0) {
        var item
        var itemForExchange
        var currentIndex = this.currentIndex

        if (event.ctrlKey) {
          switch (event.keyCode) {
            case 17:
              this.$emit('update:moving', true)
              break
            case 37:
            case 38:
              if (currentIndex > 0) {
                item = this.formItemList[currentIndex]
                itemForExchange = this.formItemList[currentIndex - 1]

                this.$set(this.formItemList, currentIndex, itemForExchange)
                this.$set(this.formItemList, currentIndex - 1, item)
              }
              break
            case 39:
            case 40:
              if (currentIndex < this.formItemList.length - 1) {
                item = this.formItemList[currentIndex]
                itemForExchange = this.formItemList[currentIndex + 1]

                this.$set(this.formItemList, currentIndex, itemForExchange)
                this.$set(this.formItemList, currentIndex + 1, item)
              }
              break
          }
        } else {
          switch (event.keyCode) {
            case 37:
            case 38:
              if (currentIndex > 0) {
                itemForExchange = this.formItemList[currentIndex - 1]
                this.$emit('update:currentItemName', itemForExchange.name)
              }
              break
            case 39:
            case 40:
              if (currentIndex < this.formItemList.length - 1) {
                itemForExchange = this.formItemList[currentIndex + 1]
                this.$emit('update:currentItemName', itemForExchange.name)
              }
              break
          }
        }
      }
    }, 200, {trailing: false}),
    handleKeyUp: throttle(function (event) {
      if (event.keyCode === 17) {
        this.$emit('update:moving', false)
      }
    }, 200),
    addDocumentKeyEventListener (event) {
      document.addEventListener('keydown', this.handleKeydown)
      document.addEventListener('keyup', this.handleKeyUp)
    },
    removeDocumentKeyEventListener (event) {
      document.removeEventListener('keydown', this.handleKeydown)
      document.removeEventListener('keyup', this.handleKeyUp)
    },
    itemChange(item,formItemList){
      item.hidden=!item.hidden
      formItemList.forEach((i)=>{
        if(i.name==item.name){
          formItemList.forEach((it)=>{
            if(it.name=='textFieldContent'){
              it.hidden = item.hidden
            }
          })
        }
      })
    },
    toggle () {
      if (this.dialogVisible) {
        this.close()
      } else {
        this.open()
      }
    },
    open () {
      this.generateFormItemList()
      this.dialogVisible = true
    },
    confirm () {
      var result = {}
      var vm = this

      this.formItemList.forEach((item, index) => {
        result[item.name] = deepClone(item)
        result[item.name].order = index
      })
      for(var key in result){
        if(key=='customField'){
          result['textFieldContent'].order=result[key].order
        }
      }
      this.$emit('confirmNewItemsConfig', {
        data: result,
        done: function () {
          vm.$emit('editingFormItemsConfigChange', null)
          vm.$emit('update:currentItemName', '')
          vm.dialogVisible = false
        }
      })
      window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-高级搜索布局保存'])
    },
    close () {
      this.$emit('update:currentItemName', '')
      this.$emit('editingFormItemsConfigChange', null)
      this.dialogVisible = false
    },
    updateGuidanceSuccess () {
      let guidance = this.$getCache('guidance')
      this.getNoviceKeyStatus = guidance || {'advancedSearchCustomLayoutDialog': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
    }
  },
  beforeMount () {
    this.updateGuidanceSuccess()
  },
  mounted () {
    // var myModal = document.getElementById('my-modal')
    // if (!myModal) {
    //   myModal = document.createElement('div')

    //   myModal.style.position = 'fixed'
    //   myModal.style.top = '0'
    //   myModal.style.bottom = '0'
    //   myModal.style.left = '0'
    //   myModal.style.right = '0'
    //   myModal.style.textAlign = 'center'
    //   myModal.style.opacity = '1'
    //   myModal.style.background = '#000'
    //   myModal.style.zIndex = '2002'
    //   myModal.style.display = 'none'

    //   myModal.setAttribute('id', 'my-modal')

    //   myModal.addEventListener('click', function (event) {
    //     event.stopPropagation()
    //   })
    //   document.body.appendChild(myModal)
    // }
  }
}
</script>
<style lang="stylus">
  .AdvancedSearchConfigDialog
    .el-switch__core
      height 14px
      &:after
        content ""
        position absolute
        border-radius 100%
        width 12px
        height 12px
        top 0px
        left 0px
        background-color #fff
    .el-switch.is-checked
      .el-switch__core
        &:after
          right 0px
          left auto

    .el-switch
      float right
      margin-top 5px
</style>



<style lang="stylus" scoped>
@media (max-width: 1440px)
  .AdvancedSearchConfigDialog
    left 620px !important
  .merge .AdvancedSearchConfigDialog
    left 440px !important
    .draggable-list-wrapper
      max-height: calc(100vh - 595px) !important
  .newPublicSideBarSideBar .AdvancedSearchConfigDialog
    left 584px !important
  .newBusinessSideBar .AdvancedSearchConfigDialog
    left 538px !important
.iconfont
  color #CCCCCC !important
  margin-left -5px
li.item
  height 30px
  line-height 30px
  user-select none
  cursor pointer
  color #000000
  padding-left 20px
  padding-right 10px
  .name
    display inline-block
    width 175px
    text-overflow ellipsis
    white-space nowrap
    overflow hidden
    line-height 30px
    height 30px
    vertical-align top
  .button
    color #FF6B6B
    padding 0 10px
li.item.is-hidden
  color #878787
  .button
    color #459AE9

li.item.current-item
  color #459AE9
  background #ecf5ff

.moving
  li.item.current-item
    background #e0eefc

.AdvancedSearchConfigDialog
    position absolute
    top 36px
    left 842px
    margin-top auto !important
    width 228px
    background #fff
    border 1px solid #ddd
    border-radius 4px
    padding 20px 20px
    line-height 20px
    box-shadow 0px 2px 4px 0px rgba(0,0,0,0.12), 0px 0px 6px 0px rgba(0,0,0,0.04)
    z-index 2003
.isNewViewDialog
  left 614px
.draggable-list-wrapper-header
  color #878787
  margin-top 10px
  margin-bottom 10px
  margin-right -3px
.draggable-list-wrapper
  max-height calc(100vh - 345px)
  margin-top 10px
  padding 0px 0px 0px 0px
  overflow-y auto
  margin-bottom 20px
  margin-left -20px
  margin-right -20px
  &::-webkit-scrollbar
    width 6px
    height 6px
    background transparent !important
  &::-webkit-scrollbar-track
    background transparent !important
  &::-webkit-scrollbar-track-piece
    ackground transparent !important
  &::-webkit-scrollbar-thumb
    border-color #ffffff
.header
  .title
    height 14px
    font-size 14px
    font-weight 400
    color #424242
    line-height 14px
  .sub-title
    margin-top 6px
    font-size 12px
    color #878787
.dialog-footer
  text-align center
</style>
